#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: yangshuang
# @software: PyCharm
# @FileName：servicefix
# @Date: 2022/4/29 10:14

import os
from git import Repo
from git.repo.fun import is_git_dir


class GitDiff(object):
    def __init__(self, local_path, repo_url, branch="master"):
        self.local_path = local_path
        self.repo_url = repo_url
        self.local_repo = None
        self.initial(branch)

    def initial(self, branch):
        """初始化git仓库"""
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)
        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            self.local_repo = Repo.clone_from(self.repo_url, to_path=self.local_path, branch=branch)
        else:
            self.local_repo = Repo(self.local_path)
        git_ = self.local_repo.git
        cur_branch = self.local_repo.active_branch
        if str(cur_branch) != branch:
            """切换分支"""
            git_.checkout(branch)
            git_.pull("--rebase")


    def branches(self):
        """获取所有分支"""
        branches = self.local_repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]


    def commits(self):
        """获取所有提交记录"""
        commit_log = self.local_repo.git.log('--pretty={"commit":"%H","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]


    def commitidDiff(self, commitid1, commitid2):
        """获取commitid不同"""
        commit_diff = self.local_repo.git.diff(commitid1, commitid2)
        with open('diffResult.diff', 'w', encoding="utf-8")as f:
            f.write(commit_diff)
        os.popen('pygmentize -f html -O full -o test.html diffResult.diff')
        return commit_diff





